package com.clothe.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.clothe.dao.IKindDAO;
import com.clothe.dto.Kind;

public class KindDAOImpl implements IKindDAO {
	private Connection conn = null;

	@Override
	public void setConn(Connection conn) {
		this.conn = conn;

	}

	@Override
	public boolean save(Kind kind) throws Exception {
		PreparedStatement ps = null;
		boolean flag = false;
		try {
			String sql = "insert into kind(kind_name,season) values(?,?)";
			ps = conn.prepareStatement(sql);
			ps.setString(1, kind.getKindName());
			ps.setString(2, kind.getSeason());
			if (ps.executeUpdate() > 0)
				flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			ps.close();
		}
		return flag;
	}

	@Override
	public boolean delete(int id) throws Exception {
		PreparedStatement ps = null;
		boolean flag = false;
		try {
			String sql = "delete from kind where id=?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			if (ps.executeUpdate() > 0)
				flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			ps.close();
		}
		return flag;
	}

	@Override
	public boolean update(Kind kind) throws Exception {
		PreparedStatement ps = null;
		boolean flag = false;
		try {
			String sql = "update kind set kind_name = ?,season = ? where id=?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, kind.getKindName());
			ps.setString(2, kind.getSeason());
			ps.setInt(3, kind.getId());
			if (ps.executeUpdate() > 0)
				flag = true;
		} catch (Exception e) {
			ps.close();
			e.printStackTrace();
		}
		return flag;
	}

	@Override
	public Kind get(int id) throws Exception {
		PreparedStatement ps = null;
		ResultSet rs = null;
		Kind kind = null;
		try {
			String sql = "select * from kind where id = ?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			rs = ps.executeQuery();
			if (rs.next()) {
				kind = new Kind();
				kind.setId(rs.getInt("id"));
				kind.setKindName(rs.getString("kind_name"));
				kind.setSeason(rs.getString("season"));

			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			ps.close();
		}
		return kind;
	}

	@Override
	public List<Kind> list() throws Exception {
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Kind> kindlist = null;
		Kind kind = null;
		try {
			kindlist = new ArrayList<Kind>();
			String sql = "select * from kind";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				kind = new Kind();
				kind.setId(rs.getInt("id"));
				kind.setSeason(rs.getString("season"));
				kindlist.add(kind);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			ps.close();
		}
		return kindlist;

	}

}
